package com.chapter03;

import com.bdqn.util.JDBCUtils;

import java.sql.*;
import java.util.Scanner;

public class Test05_Login {
    public static void main(String[] args) throws SQLException, ClassNotFoundException {
        Scanner input = new Scanner(System.in);
        System.out.print("请输入用户名：");
        String userName = input.nextLine();
        System.out.print("请输入密码：");
        String pwd = input.nextLine();

        boolean result = login(userName, pwd);

        if (result) {
            System.out.println("登录成功");
        } else {
            System.out.println("登录失败");
        }

    }

    private static boolean login(String userName, String pwd) throws SQLException, ClassNotFoundException {
        boolean result = false;

        Connection connection = JDBCUtils.getConnection();
//        Statement statement = connection.createStatement();

//        String sql = "SELECT COUNT(*) from student WHERE StudentNo='" + userName
//                + "' AND LoginPwd='" + pwd + "';";
        String sql = "SELECT COUNT(*) from student WHERE StudentNo=? AND LoginPwd=?;";
        PreparedStatement preparedStatement = connection.prepareStatement(sql);
        preparedStatement.setObject(1,userName);
        preparedStatement.setObject(2,pwd);


        System.out.println(sql);

//        ResultSet rs = statement.executeQuery(sql);
        ResultSet rs = preparedStatement.executeQuery();

        int cnt = 0;
        if (rs.next()) {
            cnt = rs.getInt(1);
        }

        if (cnt > 0) {
            // 查询到数据
            result = true;
        }

        rs.close();
        preparedStatement.close();
        connection.close();


        return result;
    }
}
